package com.xqnode.boot.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.xqnode.boot.common.JsonResult;
import com.xqnode.boot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/registry")
    public JsonResult registry(@RequestBody User user) {
        user.setPassword(SecureUtil.md5(user.getPassword()));
        user.setCreateTime(new Date());
        Boolean ret = stringRedisTemplate.opsForValue().setIfAbsent(user.getLoginName(), JSONUtil.toJsonStr(user));
        if (ret == null || !ret) {
            return JsonResult.errorResult("注册失败，用户已存在");
        }
        return JsonResult.dataResult(user);
    }

    @PostMapping("/login")
    public JsonResult login(@RequestBody User user) {
        String userStr = stringRedisTemplate.opsForValue().get(user.getLoginName());
        if (StrUtil.isBlank(userStr)) {
            return JsonResult.errorResult("登录失败");
        }
        User userBean = JSONUtil.toBean(userStr, User.class);
        String password = userBean.getPassword();
        if (!password.equals(SecureUtil.md5(user.getPassword()))) {
            return JsonResult.errorResult("登录失败");
        }
        return JsonResult.dataResult(userBean);
    }
}
